package com.atguigu.tingshu.search.task;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.SortOrder;
import co.elastic.clients.elasticsearch._types.aggregations.Aggregate;
import co.elastic.clients.elasticsearch._types.aggregations.Aggregation;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import com.atguigu.tingshu.model.search.AlbumInfoIndex;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.stream.Collectors;

@Component
public class SearchAlbumFromEs {
    @Autowired
    private ElasticsearchClient elasticsearchClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @SneakyThrows
    @Scheduled(cron = "0 0 3 * * ?")
    public void searchRank(){

        String[] stringArray = new String[] {"hotScore","playStatNum","subscribeStatNum","buyStatNum","commentStatNum"};

        //构建一个构造器
        SearchRequest.Builder builder = new SearchRequest.Builder();
        //指定查询的域
        builder.index("albuminfo_java1030");
        builder.size(0);
            builder.aggregations(
                    "category1Id",
                    subAgg -> {
                        Aggregation.Builder.ContainerBuilder category1IdAgg = subAgg.terms(
                                //查询category1Id字段，显示15条数据
                                terms -> terms.field("category1Id").size(15)
                        );
                        for (String arry :
                                //循环stringArray数组
                                stringArray) {
                            category1IdAgg.aggregations(arry, Agg->Agg.topHits(
                                    topHits -> topHits.sort(//排序
                                            sort -> sort.field(
                                                    filed -> filed.field(arry).order(SortOrder.Desc)//根据数组的元素排序
                                            )
                                    ).size(10))//取前十个
                            );
                        }
                        //返回
                        return category1IdAgg;
                    }
            );
        //执行查询
        SearchResponse<AlbumInfoIndex> search = elasticsearchClient.search(builder.build(), AlbumInfoIndex.class);
        //获取聚合数据
        Map<String, Aggregate> aggregations = search.aggregations();
        if (aggregations != null){
            //获取通对象
            Aggregate aggregate = aggregations.get("category1Id");
            aggregate.lterms().buckets().array().stream().forEach(longTermsBucket -> {
                //获取子聚合。获取桶里面的数据，只有6个专辑数据
                Map<String, Aggregate> aggregationsMap = longTermsBucket.aggregations();
                //获取一级分类id
                long key = longTermsBucket.key();
                if (aggregationsMap != null) {
                    for (String sss :
                            stringArray   ) {
                        //根据别名获取
                        Aggregate topHitsInfo = aggregationsMap.get(sss);
                        List<AlbumInfoIndex> collectList = topHitsInfo.topHits().hits().hits().stream().map(album ->
                                //将数据换成AlbumInfoIndex，转换为list
                                album.source() .to(AlbumInfoIndex.class)).collect(Collectors.toList());
                        //写进Redis，分类id做大key，hotScore做小key
                        redisTemplate.opsForHash().put("Rank:"+key,sss,collectList);
                    }
                }
            });
        }

    }
}
